package com.infinitus.activity.util;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  vo 转换工具
 * 
 */
public class VoTransferUtil {
	
	public static final Logger LOG = LoggerFactory.getLogger(VoTransferUtil.class);
	
	/**
	 * 两对象相同属性拷贝
	 * @param entity
	 * @param vo
	 * @return
	 */
	public static <T>  T transferToVo(Object entity, T vo) {
		try {
			if (entity == null || vo == null) {
				return null;
			}
			Field[] entityFields = entity.getClass().getDeclaredFields();
			Field[] voFields = vo.getClass().getDeclaredFields();
			for (Field enf : entityFields) {
				for (Field vof : voFields) {
					enf.setAccessible(true);
					vof.setAccessible(true);
					if (vof.get(vo) != null) {
						continue;
					}
					if (enf.getName().equals(vof.getName())) {
						if (enf.getType().equals(vof.getType())) {
							vof.set(vo, enf.get(entity));							
						}else if (enf.getType().equals(Date.class) && vof.getType().equals(String.class)) {//date 转 字符串
							try {
								Date entitydDate = (Date) enf.get(entity);
								vof.set(vo, DatetimeFormatUtil.datetimeFormat(entitydDate));
							} catch (Exception e) {
								LOG.warn("对象属性拷贝失败！", e);
							}
						}
						break;
					}
				}
			}
		} catch (Exception e) {
			LOG.error("对象属性拷贝失败！", e);
			vo = null;
		}
		return vo;
	}
	
	/**
	 * 两LIST间同名属性拷贝
	 * @param entitys
	 * @param vos
	 * @param voClass
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static  List transferToVo(List entitys, List vos, Class voClass) throws InstantiationException, IllegalAccessException {
		if (entitys != null && vos != null) {
			Object instance = null;
			for (int i = 0; i < entitys.size(); i++) {
				instance = voClass.newInstance();
				transferToVo(entitys.get(i), instance);
				vos.add(instance);
			}
		}
		return vos;
	}
	
}
